{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# gate_scheduling_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/gate_scheduling_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/gate_scheduling_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Gate Scheduling problem.\n",
    "\n",
    "We have a set of jobs to perform (duration, width).\n",
    "We have two parallel machines that can perform this job.\n",
    "One machine can only perform one job at a time.\n",
    "At any point in time, the sum of the width of the two active jobs does not\n",
    "exceed a max_width.\n",
    "\n",
    "The objective is to minimize the max end time of all jobs.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ortools.sat.colab import visualization\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def main(_) -> None:\n",
    "    \"\"\"Solves the gate scheduling problem.\"\"\"\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    jobs = [\n",
    "        [3, 3],  # [duration, width]\n",
    "        [2, 5],\n",
    "        [1, 3],\n",
    "        [3, 7],\n",
    "        [7, 3],\n",
    "        [2, 2],\n",
    "        [2, 2],\n",
    "        [5, 5],\n",
    "        [10, 2],\n",
    "        [4, 3],\n",
    "        [2, 6],\n",
    "        [1, 2],\n",
    "        [6, 8],\n",
    "        [4, 5],\n",
    "        [3, 7],\n",
    "    ]\n",
    "\n",
    "    max_width = 10\n",
    "\n",
    "    horizon = sum(t[0] for t in jobs)\n",
    "    num_jobs = len(jobs)\n",
    "    all_jobs = range(num_jobs)\n",
    "\n",
    "    intervals = []\n",
    "    intervals0 = []\n",
    "    intervals1 = []\n",
    "    performed = []\n",
    "    starts = []\n",
    "    ends = []\n",
    "    demands = []\n",
    "\n",
    "    for i in all_jobs:\n",
    "        # Create main interval.\n",
    "        start = model.new_int_var(0, horizon, f\"start_{i}\")\n",
    "        duration = jobs[i][0]\n",
    "        end = model.new_int_var(0, horizon, f\"end_{i}\")\n",
    "        interval = model.new_interval_var(start, duration, end, f\"interval_{i}\")\n",
    "        starts.append(start)\n",
    "        intervals.append(interval)\n",
    "        ends.append(end)\n",
    "        demands.append(jobs[i][1])\n",
    "\n",
    "        # Create an optional copy of interval to be executed on machine 0.\n",
    "        performed_on_m0 = model.new_bool_var(f\"perform_{i}_on_m0\")\n",
    "        performed.append(performed_on_m0)\n",
    "        start0 = model.new_int_var(0, horizon, f\"start_{i}_on_m0\")\n",
    "        end0 = model.new_int_var(0, horizon, f\"end_{i}_on_m0\")\n",
    "        interval0 = model.new_optional_interval_var(\n",
    "            start0, duration, end0, performed_on_m0, f\"interval_{i}_on_m0\"\n",
    "        )\n",
    "        intervals0.append(interval0)\n",
    "\n",
    "        # Create an optional copy of interval to be executed on machine 1.\n",
    "        start1 = model.new_int_var(0, horizon, f\"start_{i}_on_m1\")\n",
    "        end1 = model.new_int_var(0, horizon, f\"end_{i}_on_m1\")\n",
    "        interval1 = model.new_optional_interval_var(\n",
    "            start1,\n",
    "            duration,\n",
    "            end1,\n",
    "            ~performed_on_m0,\n",
    "            f\"interval_{i}_on_m1\",\n",
    "        )\n",
    "        intervals1.append(interval1)\n",
    "\n",
    "        # We only propagate the constraint if the tasks is performed on the machine.\n",
    "        model.add(start0 == start).only_enforce_if(performed_on_m0)\n",
    "        model.add(start1 == start).only_enforce_if(~performed_on_m0)\n",
    "\n",
    "    # Width constraint (modeled as a cumulative)\n",
    "    model.add_cumulative(intervals, demands, max_width)\n",
    "\n",
    "    # Choose which machine to perform the jobs on.\n",
    "    model.add_no_overlap(intervals0)\n",
    "    model.add_no_overlap(intervals1)\n",
    "\n",
    "    # Objective variable.\n",
    "    makespan = model.new_int_var(0, horizon, \"makespan\")\n",
    "    model.add_max_equality(makespan, ends)\n",
    "    model.minimize(makespan)\n",
    "\n",
    "    # Symmetry breaking.\n",
    "    model.add(performed[0] == 0)\n",
    "\n",
    "    # Solve model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solver.solve(model)\n",
    "\n",
    "    # Output solution.\n",
    "    if visualization.RunFromIPython():\n",
    "        output = visualization.SvgWrapper(solver.objective_value, max_width, 40.0)\n",
    "        output.AddTitle(f\"Makespan = {solver.objective_value}\")\n",
    "        color_manager = visualization.ColorManager()\n",
    "        color_manager.SeedRandomColor(0)\n",
    "\n",
    "        for i in all_jobs:\n",
    "            performed_machine = 1 - solver.value(performed[i])\n",
    "            start_of_task = solver.value(starts[i])\n",
    "            d_x = jobs[i][0]\n",
    "            d_y = jobs[i][1]\n",
    "            s_y = performed_machine * (max_width - d_y)\n",
    "            output.AddRectangle(\n",
    "                start_of_task,\n",
    "                s_y,\n",
    "                d_x,\n",
    "                d_y,\n",
    "                color_manager.RandomColor(),\n",
    "                \"black\",\n",
    "                f\"j{i}\",\n",
    "            )\n",
    "\n",
    "        output.AddXScale()\n",
    "        output.AddYScale()\n",
    "        output.Display()\n",
    "    else:\n",
    "        print(\"Solution\")\n",
    "        print(f\"  - makespan = {solver.objective_value}\")\n",
    "        for i in all_jobs:\n",
    "            performed_machine = 1 - solver.value(performed[i])\n",
    "            start_of_task = solver.value(starts[i])\n",
    "            print(\n",
    "                f\"  - Job {i} starts at {start_of_task} on machine\"\n",
    "                f\" {performed_machine}\"\n",
    "            )\n",
    "        print(solver.response_stats())\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
